const fs = require('fs')
const { desktopCapturer, navigator } = require('electron')

const menuTemplate = [
  {
    label: '文件',
    submenu: [
      {
        label: '新建',
        accelerator: 'CmdOrCtrl+N',
        click: () => {
          console.log('new file')
        },
      },
    ],
  },
  {
    label: '编辑',
    submenu: [
      {
        label: '复制',
        accelerator: 'CmdOrCtrl+C',
        selector: 'copy:',
      },
      {
        label: '粘贴',
        accelerator: 'CmdOrCtrl+V',
        selector: 'paste:',
      },
    ],
  },
  {
    label: '操作',
    submenu: [
      {
        label: '截图',
        click: async () => {
          // 获取源列表
          const sources = await desktopCapturer.getSources({
            types: ['window', 'screen'],
          })

          // 选择第一个源
          const stream = await navigator.mediaDevices.getUserMedia({
            audio: false,
            video: {
              mandatory: {
                chromeMediaSource: 'desktop',
                chromeMediaSourceId: sources[0].id,
              },
            },
          })

          // 获取截图并保存
          const buffer = stream.getVideoTracks()[0].getPhoto()
          fs.writeFileSync('screenshot.png', buffer)

          // 释放资源
          stream.getTracks().forEach((track) => track.stop())
        },
      },
    ],
  },
]

module.exports = menuTemplate
